#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"

#include "esp_libc.h"

#include "./inc/sniffer.h"
#include "./inc/app_wifi.h"
#include "./inc/http_client.h"

#define TAG "user_main"


static void upload_data_cb(sniffer_mac_info_t *buf,uint16_t len)
{
    uint16_t i,j;
    char print_buf[30];
    char* post_data;
    uint8_t me_mac[6];
    EventBits_t res;
    
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
    esp_wifi_connect();
    ESP_LOGI(TAG, "wifi_init_sta finished.");

    post_data = malloc(len * 14 +  18);
    if(post_data != NULL)
    {
        *post_data = 'm';
        *(post_data + 1) = '=';
        ESP_ERROR_CHECK(esp_wifi_get_mac(ESP_IF_WIFI_STA, me_mac));
        for(j=0; j<6;++j)
        {
            sprintf(post_data + j * 2 + 2, "%02x", me_mac[j]);
        }
        *(post_data + 14) = '&';
        *(post_data + 15) = 'd';
        *(post_data + 16) = '=';
        for(i=0 ;i<len ;++i)
        {
            for(j=0; j<6;++j)
            {
                sprintf(post_data + j * 2 + i * 14 + 17, "%02x", (buf + i)->mac[j]);
            }
            sprintf(post_data + i * 14 + 29, "%02x", (char)(buf + i)->rssi);
        }

        res = xEventGroupWaitBits(app_wifi_event_group, WIFI_CONNECTED_BIT,false, true, 10000 / portTICK_PERIOD_MS);
        if( (res & WIFI_CONNECTED_BIT) != 0)
        {
            ESP_LOGI(TAG, "Connected to AP, begin http client.");
            //http_rest();
            
            for(i=0 ;i<len ;++i)
            {
                for(j=0; j<6;++j)
                {
                    sprintf(print_buf + j * 3, "%02x:", (buf + i)->mac[j]);
                }
                sprintf(print_buf + 17, " %d", (buf + i)->rssi);
                printf("%s\n",print_buf);
            }
            printf("\n");
            http_post("http://bs.udoudou.cn/test.php" ,post_data);
        }
    }
    else
    {
        ESP_LOGI(TAG,"malloc fail!");
    }

    esp_wifi_disconnect();
}

/******************************************************************************
 * FunctionName : app_main
 * Description  : entry of user application, init user function here
 * Parameters   : none
 * Returns      : none
*******************************************************************************/
void app_main(void)
{
    printf("SDK version:%s\n", esp_get_idf_version());

    ESP_ERROR_CHECK(nvs_flash_init());
    app_wifi_init();
    xEventGroupWaitBits(app_wifi_event_group, START_BIT,false, true, portMAX_DELAY);
    sniffer_init();
    sniffer_start();
    sniffer_set_read_cb(&upload_data_cb);
}
